package com.mq.config;

import com.mq.receiver.DirectAckReceiver;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xwj
 * @date 2019/6/18
 */
@Configuration
public class DirectRabbitConfig {
    @Bean
    public Queue CalonDirectQueue() {
        return new Queue("CalonDirectQueue", true);
    }

    @Bean
    public Queue CalonDirectQueueAck() {
        return new Queue("CalonDirectQueueAck", true);
    }

    @Bean
    DirectExchange CalonDirectExchange() {
        return new DirectExchange("CalonDirectExchange");
    }

    @Bean
    Binding bindingDirect() {
        return BindingBuilder.bind(CalonDirectQueue()).to(CalonDirectExchange()).with("CalonDirectRouting");
    }

    @Bean
    Binding bindingDirectAck() {
        return BindingBuilder.bind(CalonDirectQueueAck()).to(CalonDirectExchange()).with("CalonDirectQueueAckRouting");
    }

    @Autowired
    private CachingConnectionFactory connectionFactory;
    @Autowired
    private DirectAckReceiver directAckReceiver;

    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setConcurrentConsumers(1);
        container.setMaxConcurrentConsumers(1);
        // 开启手动确认
        // AcknowledgeMode.NONE：不确认
        // AcknowledgeMode.AUTO：自动确认
        // AcknowledgeMode.MANUAL：手动确认
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);

        container.setQueues(CalonDirectQueueAck());
        container.setMessageListener(directAckReceiver);
        return container;
    }
}
